package Server.Game;

import Server.Game.Questions.Question;
import Server.Game.Questions.XMLReader;
import Server.Sessions.OutboundMessages;
import shared.Messages.DcWinMessage;
import shared.Messages.QuestionMessage;
import shared.Player.Player;

public class GameOK extends Thread {
	OutboundMessages outQueue;
	Player p0;
	Player p1;
	XMLReader xmlReader = new XMLReader("Kysimused.xml");
	int allFalseAnswersPerQuestion = 0;
	Player winner;
	int GameNo;
	int answeredCorrectly;
	public Question question;

	TurnController tc;
	int turnPlayerId;
	boolean moved;
	boolean dcBreak = false;

	public GameOK(OutboundMessages outQueue, int GameNo, Player p0, Player p1) {
		this.outQueue = outQueue;
		this.GameNo = GameNo;
		this.p0 = p0;
		this.p1 = p1;
		question = xmlReader.getQuestionL().getRandomQuestion();

		outQueue.addMessage(new QuestionMessage(question, GameNo, turnPlayerId, p0.points, p1.points));

		tc = new TurnController(outQueue, GameNo);
		turnPlayerId = tc.nextTurn();
		start();
	}



	public void run() {
		while (true) {
			moved = false;
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				System.out.println("Sleep kaktestatud!");
				break;
			}
			switch (turnPlayerId) {
			case 1:
				if (p0.nextTurn) {
					moved = true;		
					turnPlayerId = tc.nextTurn();
					p0.nextTurn = false;
				}
				break;
			case 2:
				if (p1.nextTurn) {
					moved = true;
					turnPlayerId = tc.nextTurn();
					p1.nextTurn = false;
				}
				break;

			}
			if(p0.dc || p1.dc){
				outQueue.addMessage(new DcWinMessage(GameNo, "DC (GAMEOK?)"));
				dcBreak = true;
				break;
			}
			if(question.changeQuestion()){
				System.out.println("GAMEOK changeQuestion()=true");
				question = xmlReader.getQuestionL().getRandomQuestion();
				p1.points += p1.currentpoints;
				p1.currentpoints = 0;
				p0.points += p0.currentpoints;
				p0.currentpoints = 0;
				outQueue.addMessage(new QuestionMessage(question, GameNo, turnPlayerId, p0.points,p1.points));
			}
		}
	}

}

